Page({
  data: {
    order_info: {},
    show: false,
    tempInfo: {
      name: '',
      phone: '',
      address: ['省份', '城市', '区'],
    },
    region: ['省份', '城市', '区'],
    orderId: '',
  },

  async onLoad(options) {
    this.setData({ orderId: options.id });
    await this.queryInfo();
  },

  async queryInfo() {
    await wx.request({
      url: `http://1.94.51.11:8850/user/queryOrder/${this.data.orderId}`,
      header: {
        Cookie: wx.getStorageSync('session'),
      },
      success: res => {
        this.setData({ order_info: res.data.data });
      },
    });
  },

  // 关闭弹窗
  onClose() {
    this.setData({ show: false });
  },

  // 打开弹窗
  updateInfo() {
    this.setData({
      show: true,
      name: '现有姓名',
      phone: '现有手机号',
      region: ['现有省', '现有市', '现有区'],
    });
  },

  onName: function (e) {
    this.setData({ 'tempInfo.name': e.detail.value });
  },

  onPhone: function (e) {
    this.setData({ 'tempInfo.phone': e.detail.value });
  },

  // 显示省市地区
  onRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      'tempInfo.address': e.detail.value,
    });
  },

  // 提交修改
  onConfirm: function () {
    wx.request({
      url: 'http://1.94.51.11:8850/user/updateOrder',
      method: 'PUT',
      header: {
        Cookie: wx.getStorageSync('session'),
      },
      data: {
        id: this.data.orderId,
        name: this.data.tempInfo.name || null,
        phone: this.data.tempInfo.phone || null,
        address: this.data.tempInfo.address.join(' '),
      },
      success: res => {
        console.log(res);
        wx.showToast({
          title: '提交成功',
          icon: 'success',
        });
        this.queryInfo();
        // 关闭弹窗
        this.setData({
          show: false,
        });
      },
    });
  },

  // 删除订单
  deleteInfo: function () {
    wx.showModal({
      title: '删除订单',
      content: '确定要删除订单吗？',
      success: res => {
        if (res.confirm) {
          wx.request({
            url: `http://1.94.51.11:8850/user/deleteOrder/${this.data.orderId}`,
            method: 'DELETE',
            header: {
              Cookie: wx.getStorageSync('session'),
            },
            success: res => {
              console.log(res);
              wx.showToast({
                title: '删除成功',
                icon: 'success',
              });
              wx.navigateBack();
            },
          });
        }
      },
    });
  },
});
